package com.berchen.utils;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PoiExcelUtils {
    public static List<Map<String, Object>> readBill(String filename, InputStream in) throws IOException {

        Workbook workbook = null;
        if (filename.endsWith(".xls")) {
            workbook = new HSSFWorkbook(in);
        } else if (filename.endsWith(".xlsx")) {
            workbook = new XSSFWorkbook(in);
        }
        Sheet sheetAt = workbook.getSheetAt(0);
        Row row = sheetAt.getRow(0);
        short lastCellNum = row.getLastCellNum();
        int lastRowNum = sheetAt.getLastRowNum();
        List<Map<String, Object>> list = new ArrayList<>();
        for (int i = 1; i <= lastRowNum; i++) {
            Map<String, Object> map = new HashMap<>();
            row = sheetAt.getRow(i);
            for (int j = 0; j < lastCellNum; j++) {

                String key = "";
                switch (j) {
                    case 0:
                        key = "createDate";
                        break;
                    case 1:
                        key = "price";
                        break;
                    case 2:
                        key = "instruction";
                        break;
                    case 3:
                        key = "remark";
                        break;
                    case 4:
                        key = "type";
                        break;
                    default:
                        break;
                }
                Cell cell = row.getCell(j);
                if (cell == null) {
                    map.put(key, "");
                } else {
                    cell.setCellType(CellType.STRING);
                    if (j == 4) {
                        map.put(key, cell.getStringCellValue().equals("支出") == true ? 1 : 2);
                    } else{
                        map.put(key, cell.getStringCellValue());
                    }
                }
            }
            list.add(map);
        }
        return list;
    }
}